 <!--
 * @Author: zeng_ze
 * @Date: 2019-11-7
 * @Description: 系统管理下的用户管理
 -->
<template>
  <div class="main-wrapper user-container">
    <fks-query-page
      ref="userTable"
      v-loading="listLoading"
      :data="tableData"
      :total="total"
      :page-size.sync="pageSize"
      :current-page.sync="currentPage"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 50, 100]"
      :element-loading-text="LANG.LOADING"
      :table-name="LANG.USER_LIST"
      @query="getAllUsers"
      @selection-change="changeChecked"
      @sort-change="sortHandler"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-input
            v-model="userName"
            size
            :placeholder="LANG.USER_SEARCH_PLACEHOLDER"
            class="single-searchBox-item"
            clearable
            maxlength="50"
            @clear="serch"
            @keyup.enter.native="serch"
          >
            <fks-button slot="append" icon="fks-icon-search" @click="serch" />
          </fks-input>
          <!-- 导出用户 -->
          <fks-button v-permission:1="['user:export']" @click="exportPost">
            <i class="fks-icon-export" />
            <span style="margin-left: 8px">{{ LANG.EXPORT }}</span>
          </fks-button>
          <!-- 用户导入 -->
          <fks-button v-permission:1="['user:import']" @click="openDialog">
            <i class="fks-icon-import" />

            <span style="margin-left: 8px; vertical-align: center">
              {{ LANG.IMPORT }}
            </span>
          </fks-button>
          <fks-button
            v-permission:1="['user:add']"
            icon="fks-icon-plus"
            type="primary"
            @click="add"
          >
            <span style="= vertical-align: center">{{ LANG.ADD }}</span>
          </fks-button>
        </div>
      </template>
      <template>
        <fks-table-column type="selection" width="55" />
        <fks-table-column type="index" align="center" label="#">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </fks-table-column>
        <!-- 姓名 -->
        <fks-table-column
          prop="userFullname"
          :label="LANG.USER_FULL_NAME"
          is-link
          sortable="custom"
          min-width="100px"
          @link="gotoView"
        />
        <!-- 用户名 -->
        <fks-table-column
          prop="userName"
          :label="LANG.USERNAME"
          min-width="90px"
        />
        <fks-table-column
          prop="sex"
          :label="LANG.SEX"
          sortable="custom"
          width="120"
        />
        <!-- 邮箱 -->
        <fks-table-column prop="email" :label="LANG.EMAIL" min-width="150" />
        <!-- 联系方式 -->
        <fks-table-column prop="phone" :label="LANG.PHONE" min-width="130" />
        <fks-table-column prop="accountPeriod" :label="LANG.ACCOUNT_PERIOD">
          <div slot-scope="scope">
            <span v-if="scope.row.accountPeriod == 1" type="success">
              {{ LANG.LANG_TIME }}
            </span>
            <span v-if="scope.row.accountPeriod == 2" type="info">
              {{ LANG.SHORT_TIME }}
            </span>
          </div>
        </fks-table-column>
        <fks-table-column prop="accountStatus" :label="LANG.ACCOUNT_STATUS">
          <div slot-scope="scope">
            <fks-tag v-if="scope.row.accountStatus == 1" type="success">
              {{ LANG.ACTIVATE }}
            </fks-tag>
            <fks-tag v-if="scope.row.accountStatus == 2" type="warning">
              {{ LANG.BLOCKED }}
            </fks-tag>
            <fks-tag v-if="scope.row.accountStatus == 3" type="danger">
              {{ LANG.LOGOUT }}
            </fks-tag>
          </div>
        </fks-table-column>
        <fks-table-column :label="LANG.OPERATION" width="150" align="left">
          <template slot-scope="scope">
            <fks-button
              v-permission:1="['user:edit']"
              type="text"
              @click.stop="editClick(scope.row)"
            >
              {{ LANG.EDIT }}
            </fks-button>
            <fks-button
              v-permission:1="['user:role']"
              type="text"
              @click.stop="viewRoles(scope.row)"
            >
              {{ LANG.VIEW_ROLE }}
            </fks-button>
            <fks-dropdown v-permission:1="['user:more']" trigger="click">
              <fks-button
                icon="fks-icon-more"
                type="text"
                min-width="28px"
                class="more"
                @click.stop
              />
              <fks-dropdown-menu slot="dropdown">
                <fks-dropdown-item
                  v-if="scope.row.accountStatus != 2"
                  @click.native="lock(scope.row)"
                >
                  {{ LANG.LOCK }}
                </fks-dropdown-item>
                <fks-dropdown-item
                  v-if="scope.row.accountStatus != 1"
                  @click.native="active(scope.row)"
                >
                  {{ LANG.ACTIVATE }}
                </fks-dropdown-item>
                <fks-dropdown-item
                  v-if="
                    scope.row.accountStatus == 1 || scope.row.accountStatus == 2
                  "
                  @click.native="logOff(scope.row)"
                >
                  <span style="color: #ff4d4f">{{ LANG.LOGOUT }}</span>
                </fks-dropdown-item>
              </fks-dropdown-menu>
            </fks-dropdown>
          </template>
        </fks-table-column>
      </template>
    </fks-query-page>
    <!-- 查看用户角色 列表 -->
    <fks-dialog
      :visible.sync="roleVisible"
      :append-to-body="true"
      destroy-on-close
      :title="LANG.USER_ROLES"
    >
      <div class="role">
        <fks-query-page
          v-loading="roleLoading"
          class="role-list"
          :data="roleData"
          :total="roleTotal"
          :page-size.sync="rolepageSize"
          :current-page.sync="rolecurrentPage"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          :element-loading-text="LANG.LOADING"
          :table-name="LANG.ROLE_LIST"
          @query="getRoles"
        >
          <template>
            <fks-table-column type="index" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </fks-table-column>
            <fks-table-column prop="name" :label="LANG.ROLE_NAME" />
            <fks-table-column prop="code" :label="LANG.ROLE_CODE" />
          </template>
        </fks-query-page>
      </div>
      <div slot="footer" style="text-align: right" />
    </fks-dialog>
    <fks-dialog
      :visible.sync="exportVisible"
      :append-to-body="true"
      width="800px"
      destroy-on-close
      :title="exportName"
      class="importUser"
      @close="cancelExoport"
    >
      <div slot="title">
        <i class="fks-icon-import" :style="{ color: theme }" />
        <span style="margin-left: 8px">{{ LANG.IMPORT }}</span>
      </div>
      <fks-form label-width="70px">
        <fks-form-item :label="LANG.TEMPLATE_UPLOAD" :span="24">
          <fks-upload
            ref="upload"
            :class="{ chinese: isChinese, english: !isChinese }"
            :action="uploadUrl"
            drag
            name="file"
            :headers="{
              'Fawkes-Auth': ACESS_TOKEN
            }"
            :with-credentials="true"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx"
            :file-list="fileList"
            :http-request="importUsers"
          >
            <i class="fks-icon-upload" />
            <div class="fks-upload__text">
              {{ LANG.DRAG_FILE }}
              <em>{{ LANG.CLICK_UPLOAD }}</em>
              <br />
              <span>{{ LANG.SUPPORT_XLSX }}</span>
            </div>
          </fks-upload>
        </fks-form-item>
        <fks-form-item :label="LANG.TEMPLATE_DOWNLOAD">
          <fks-button
            icon="fks-icon-download"
            margin-top="10px"
            @click="exportTemplates"
          >
            {{ LANG.DOWNLOAD_TEMPLATE }}
          </fks-button>
        </fks-form-item>
      </fks-form>
      <template slot="footer">
        <fks-button type="primary" icon="fks-icon-check" @click="submit">
          <span style="margin-left: 4px">{{ LANG.SAVE }}</span>
        </fks-button>
      </template>
    </fks-dialog>
    <user-info
      v-if="userVisible"
      :user-type="userTitle"
      :data="userData"
      :visible.sync="userVisible"
    />
  </div>
</template>
 <script>
import { exportFile } from '@/utils/file'
import * as types from '@/store/Getter/getterTypes.js'
import Mix from '@/mixins/module'
import * as System from './api'
import UserInfo from './UserInfo'
export default {
  name: 'User',
  components: { UserInfo },
  mixins: [Mix],
  data() {
    return {
      userName: '',
      listLoading: true,
      userId: '',
      //用户角色 列表 加载动画
      roleLoading: true,
      //用户角色 列表 数组
      roleData: [],
      //用户角色 分页数据
      roleTotal: 0,
      rolepageSize: 20,
      rolecurrentPage: 1,
      //用户角色弹窗 显隐
      roleVisible: false,
      tableData: [],
      //新增用户、编辑用户弹窗 显隐
      userVisible: false,
      userTitle: '',
      userData: {},
      //导入用户弹出 显隐
      exportVisible: false,
      //导入用户弹窗标题
      exportName: '导入用户',
      //新增用户、编辑用户弹窗 标题
      fileList: [],
      isChinese: true,
      ACESS_TOKEN: this.$storage.get('access_token'),
      //上传的地址
      uploadUrl: '',
      title: '',
      rowData: null, //编辑时，克隆原始数据
      diffData: null, //差异数据，编辑修改保存时，只上传修改过的数据
      pageSize: 20,
      total: 0,
      currentPage: 1,
      excelExportLikeParam: {},
      account: {},
      checkedId: [],
      row: {},
      searchValue: {
        searchValue: ''
      },
      formData: {
        attachment: '',
        files: 0
      },
      sort: '',
      columnName: '',
      Form: {
        name: '',
        sex: '',
        userName: '',
        password: '',
        email: '',
        phone: '',
        orgNo: '',
        orgName: '',
        accountStatus: 1,
        //新增时 默认长期
        accountPeriod: 1
      }
    }
  },
  computed: {
    theme() {
      return this.$store.getters[types.THEME]
    },
    type() {
      return this.$store.state.portal.type
    },
    portalId() {
      return this.$store.state.portal.id
    }
  },
  created() {
    this.getAllUsers()
  },
  methods: {
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop == 'userFullname' ? 'user_fullname' : 'sex'
      }
      params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName,
        searchValue: this.userName,
        needOrg: false
      }
      this.getUserList(params)
    },
    active(row) {
      System.editUsers(
        JSON.stringify(
          Object.assign({
            userName: row.userName,
            id: row.id,
            accountStatus: 1
          })
        )
      ).then((response) => {
        if (response.status) {
          this.$message.success(this.LANG.ACTIVATE_SUCCESS)
          this.getAllUsers()
        }
      })
    },
    lock(row) {
      System.editUsers(
        JSON.stringify(
          Object.assign({
            userName: row.userName,
            id: row.id,
            accountStatus: 2
          })
        )
      ).then((response) => {
        if (response.status) {
          this.$message.success(this.LANG.LOCK_SUCCESS)
          this.getAllUsers()
        } else {
          this.$message.error(this.LANG.LOCI_FALIED)
        }
      })
    },
    logOff(row) {
      this.$confirm(this.LANG.CANCEL_TIP, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.LOGOUT,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      }).then(() => {
        System.editUsers(
          JSON.stringify({
            userName: row.userName,
            id: row.id,
            accountStatus: 3
          })
        ).then((response) => {
          if (response.status) {
            this.$message.success(this.LANG.LOGOFF_SUCCESS)
            this.getAllUsers()
          }
        })
      })
    },
    // 查看用户
    gotoView({ row }) {
      this.userVisible = true
      this.userTitle = 'view'
      this.userData = JSON.parse(JSON.stringify(row))
    },
    // //点击表格回调
    // rowClick(row) {
    //   this.$refs.userTable.$children[0].toggleRowSelection(
    //     row,
    //     this.changeSelected(row)
    //   )
    // },
    //点击后修改选中状态
    changeSelected(row) {
      let w = true
      this.checkedId.forEach((item) => {
        if (item == row.id) {
          w = false
        }
      })
      return w
    },
    // 选择用户时触发
    changeChecked(val) {
      this.checkedId = []
      val.forEach((item) => {
        this.checkedId.push(item.id)
      })
    },
    //导出用户
    exportPost() {
      this.searchValue.searchValue = this.userName
      this.excelExportLikeParam = Object.assign({}, this.searchValue)
      this.excelExportLikeParam.idList = this.checkedId
      System.exportPost(this.excelExportLikeParam).then((res) => {
        if (res.status) {
          exportFile(res)
          this.$message.success(this.LANG.EXPORTING)
        }
      })
    },
    //下载模板
    exportTemplates() {
      System.getTemplates().then((res) => {
        exportFile(res)
      })
    },
    //导入用户
    importUsers(params) {
      // 根据后台需求数据格式
      let form = new FormData()
      // 文件对象
      form.append('file', params.file)
      System.importUsers(form).then((res) => {
        if (res.data) {
          exportFile(res)
        } else {
          this.$message.success(this.LANG.IMPORT_SUCCESS)
        }
      })
    },
    //打开导入用户的弹窗
    openDialog() {
      this.exportVisible = true
      if (this.$lang === 'en') {
        this.isChinese = false
      } else {
        this.isChinese = true
      }
    },
    //新增用户 弹窗
    add() {
      this.userVisible = true
      this.userTitle = 'add'
    },
    //查看用户角色,row为用户数据
    viewRoles(row) {
      this.userId = row.id
      this.getRoles()
    },
    //获取角色列表
    getRoles() {
      System.getRoles({
        id: this.userId,
        pageNo: this.rolecurrentPage,
        pageSize: this.rolepageSize,
        portalId: this.portalId
      })
        .then((res) => {
          if (res.status && res.data) {
            this.roleData = res.data.list
            this.roleTotal = res.data.total
            this.roleVisible = true
          }
          this.roleLoading = false
        })
        .catch(() => {
          this.roleLoading = false
        })
    },
    //关闭用户角色列表弹窗
    closeRole() {
      this.roleVisible = false
    },
    //编辑用户 弹窗
    editClick(row) {
      this.userVisible = true
      this.userTitle = 'edit'
      this.userData = JSON.parse(JSON.stringify(row))
    },
    serch() {
      this.currentPage = 1
      this.getAllUsers()
    },
    //获取所有用户分页
    getAllUsers() {
      this.listLoading = true
      let param = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        searchValue: this.userName,
        sort: this.sort,
        columnName: this.columnName,
        needOrg: false
      }
      this.getUserList(param)
    },
    @permission('user:query')
    getUserList(param) {
      System.getUsers(param)
        .then((res) => {
          if (res.status) {
            this.tableData = res.data.list
            this.total = res.data.total
          }
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    //关闭导入用户弹窗
    cancelExoport() {
      this.exportVisible = false
      this.fileList = []
    },
    //提交导入用户
    submit() {
      this.$refs.upload.submit()
      this.getAllUsers()
      this.cancelExoport()
    }
  }
}
</script>
 <style lang="scss" scoped>
.role {
  height: 400px;
}
.single-searchBox-item {
  width: 30%;
  max-width: 300px;
}
.user-container {
  min-width: 668px;
}
::v-deep .role-list {
  margin-top: 0px !important;
  padding-top: 0 !important;
}
.more {
  margin-left: 5px;
  width: 28px;
}
.fks-icon-more {
  width: 28px;
}
.password {
  font-size: 12px;
}
.word {
  color: #409eff;
}
.chinese {
  ::v-deep .fks-upload-dragger {
    width: 662px;
  }
}
.english {
  ::v-deep .fks-upload-dragger {
    width: 736px;
  }
}
::v-deep .fks-dialog__body {
  padding-bottom: 0px;
}
</style>